using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace StudentManagementApplication
{
    public partial class FrmStaffInfo : Form
    {
        List<Entities.Person> personList = new List<Entities.Person>();
        List<Entities.Role> roleList = new List<Entities.Role>();
        //List<Entities.Course> courseList = new List<Entities.Course>();
        Business.PersonService personService = new Business.PersonService();
        Business.RoleService roleService = new Business.RoleService();
        Business.LoginService loginService = new Business.LoginService();
        //Business.CourseService courseService = new Business.CourseService();
        Entities.Person person = null;
        Entities.Login account = null;
        Entities.Role role = null;
        int iIndex = 0;
        
        public FrmStaffInfo()
        {
            InitializeComponent();
        }

        private void InitializeRole()
        {
            roleList = roleService.GetAllRoles();
            foreach (Entities.Role role in roleList)
            {
                if (role.RoleID != "R14")
                {
                    cmbRole.Items.Add(role.RoleID + "--" + role.RoleDetail);
                }
            }
        }

        private void InitializeStaff()
        {
            if (dgvStaffs.Rows.Count > 1)
            {
                int iCount = dgvStaffs.Rows.Count - 1;
                for (int i = 0; i < iCount; i++)
                {
                    dgvStaffs.Rows.RemoveAt(0);
                }
            }
            personList = personService.GetPersonExceptRoleID("R14");
            for (int i = 0; i < personList.Count; i++)
            {
                //Bad solution
                role = new Entities.Role();
                role = roleService.GetRoleByLoginID(personList[i].LoginID);
                //
                string[] temp = { personList[i].PersonID, personList[i].PersonName, personList[i].PersonBirth.ToShortDateString(), personList[i].PersonAdd, personList[i].PersonPhone, personList[i].PersonMail, personList[i].Picture.Length > 6 ? personList[i].Picture.Substring(6) : "", role.RoleDetail };
                dgvStaffs.Rows.Add(temp);
            }
            dgvStaffs[0, iIndex].Selected = true;
        }

        private void FindStaffByStaffID(string sStaffID)
        {
            personList = personService.GetPersonExceptRoleID("R14");
            if (dgvStaffs.Rows.Count > 1)
            {
                int iCount = dgvStaffs.Rows.Count - 1;
                for (int i = 0; i < iCount; i++)
                {
                    dgvStaffs.Rows.RemoveAt(0);
                }
            }
            for (int i = 0; i < personList.Count; i++)
            {
                if (personList[i].PersonID.ToLower().Contains(sStaffID))
                {
                    //Bad solution
                    role = new Entities.Role();
                    role = roleService.GetRoleByLoginID(personList[i].LoginID);
                    //
                    string[] temp = { personList[i].PersonID, personList[i].PersonName, personList[i].PersonBirth.ToShortDateString(), personList[i].PersonAdd, personList[i].PersonPhone, personList[i].PersonMail, personList[i].Picture.Length > 6 ? personList[i].Picture.Substring(6) : "", role.RoleDetail };
                    dgvStaffs.Rows.Add(temp);
                }
            }
            iIndex = 0;
            dgvStaffs[0, iIndex].Selected = true;
            if (dgvStaffs.Rows.Count > 1) FindStaff(dgvStaffs.Rows[iIndex].Cells[0].Value.ToString());
        }

        private void FindStaff(string sStaffID)
        {
            person = new Entities.Person();
            person = personService.GetPersonByPersonID(sStaffID);
            role = new Entities.Role();
            role = roleService.GetRoleByLoginID(person.LoginID);
            txtStaffID.Text = person.PersonID;
            txtName.Text = person.PersonName;
            dtpBirthDay.Value = person.PersonBirth.Date;
            txtAddress.Text = person.PersonAdd;
            txtPhone.Text = person.PersonPhone;
            txtMail.Text = person.PersonMail;
            if (person.Picture.Length > 6)
            {
                txtPicture.Text = person.Picture.Substring(6);
                picStaff.ImageLocation = person.Picture;
            }
            else
            {
                txtPicture.Text = string.Empty;
                picStaff.ImageLocation = string.Empty;
            }
            cmbRole.Text = role.RoleID + "--" + role.RoleDetail;
        }

        private bool IsNumber(string sPhone)
        {
            try
            {
                int.Parse(sPhone);
                return true;
            }
            catch
            {
                return false;
            }
        }

        private bool Test()
        {
            bool bResult = true;
            string sInformation = string.Empty;
            if (txtName.Text == string.Empty)
                sInformation += "Full Name is empty" + "\n";
            if ((DateTime.Now.Year - dtpBirthDay.Value.Year) < 18)
                sInformation += "The ages have to be greater than 18" + "\n";
            if (txtAddress.Text == string.Empty)
                sInformation += "Address is empty" + "\n";
            if (txtPhone.Text == string.Empty)
                sInformation += "Phone is empty" + "\n";
            if (txtPhone.Text.Length != 7)
                if(txtPhone.Text.Length != 10)
                    if(txtPhone.Text.Length != 11)
                        sInformation += "Number phone have to have 7,10 or 11 chars" + "\n";
            if (!IsNumber(txtPhone.Text))
                sInformation += "Type of phone have to be integer" + "\n";
            if (txtMail.Text == string.Empty)
                sInformation += "Mail is empty" + "\n";
            if (!txtMail.Text.Contains("@"))
                sInformation += "Mail isn't legal" + "\n";
            if (cmbRole.Text == string.Empty)
                sInformation += "Role is empty" + "\n";
            if (sInformation != string.Empty)
            {
                MessageBox.Show(sInformation, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                bResult = false;
            }
            return bResult;
        }

        private void UpdateStaffInfo()
        {
            if (Test())
            {
                person.PersonName = txtName.Text;
                person.PersonBirth = dtpBirthDay.Value.Date;
                person.PersonAdd = txtAddress.Text;
                person.PersonPhone = txtPhone.Text;
                person.PersonMail = txtMail.Text;
                person.Picture = txtPicture.Text;
                account = new Entities.Login();
                account = loginService.GetAccountByLoginID(person.LoginID);
                account.RoleID = cmbRole.Text.Substring(0, 3);
                try
                {
                    personService.UpdatePerson(person);
                    loginService.UpdateAccount(account);
                    InitializeStaff();
                }
                catch
                {
                    MessageBox.Show("Role isn't legal", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private void InsertStaffInfo()
        {
            if (Test())
            {
                person = new Entities.Person();
                account = new Entities.Login();
                person.PersonName = txtName.Text;
                person.PersonBirth = dtpBirthDay.Value.Date;
                person.PersonAdd = txtAddress.Text;
                person.PersonPhone = txtPhone.Text;
                person.PersonMail = txtMail.Text;
                person.Picture = txtPicture.Text;
                person.LoginID = CreateLoginAutomatically(txtName.Text.ToLower());
                account.LoginID = person.LoginID;
                account.RoleID = cmbRole.Text.Substring(0, 3);
                account.State = 1;
                try
                {
                    loginService.InsertAccount(account);
                    personService.InsertPerson(person);
                    iIndex = dgvStaffs.Rows.Count - 1;
                    InitializeStaff();
                }
                catch
                {
                    MessageBox.Show("Role isn't legal","Warning",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                }
            }
        }

        private string CreateLoginAutomatically(string sName)
        {
            char[] charArray = { ' ' };
            string[] nameArray = sName.Split(charArray);
            string sLoginID = string.Empty;
            while (true)
            {
                sLoginID = string.Empty;
                Random random = new Random();
                sLoginID += nameArray[nameArray.Length - 1] + nameArray[0] + random.Next(1, 100).ToString();
                Entities.Login account = loginService.GetAccountByLoginID(sLoginID);
                if (account == null)
                    break;
            }
            return sLoginID;
        }

        private void DeleteStaff()
        {
            if (dgvStaffs.CurrentRow.Index >= 0)
            {
                if (MessageBox.Show("Do you really want to delete this file?", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                {
                    try
                    {
                        personService.DeletePerson(person.PersonID);
                        loginService.DeleteAccount(person.LoginID);
                        if (iIndex > 0) iIndex--;
                        else iIndex = 0;
                        InitializeStaff();
                        FindStaff(dgvStaffs.Rows[iIndex].Cells[0].Value.ToString());
                    }
                    catch
                    {
                        MessageBox.Show("You can't delete this staff because it have references to some tables of database", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }

        private void RefreshData()
        {
            txtStaffID.Text = string.Empty;
            txtName.Text = string.Empty;
            dtpBirthDay.Value = DateTime.Now.Date;
            txtAddress.Text = string.Empty;
            txtPhone.Text = string.Empty;
            txtMail.Text = string.Empty;
            txtPicture.Text = string.Empty;
            cmbRole.Text = string.Empty;
            picStaff.Image = null;
            picStaff.ImageLocation = string.Empty;
        }

        private void FrmStaffInfo_Load(object sender, EventArgs e)
        {
            InitializeStaff();
            InitializeRole();
        }

        private void rdoInsert_CheckedChanged(object sender, EventArgs e)
        {
            RefreshData();
            txtStaffID.Enabled = false;
            btnInsert.Enabled = true;
            pictureBox1.Enabled = false;
            btnDelete.Enabled = false;
            btnUpdate.Enabled = false;
        }

        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog file = new OpenFileDialog();
            file.InitialDirectory = "Image";
            file.FileName = txtPicture.Text;
            file.ShowDialog();
            string sFileName = file.FileName;
            if(sFileName != string.Empty) txtPicture.Text = sFileName.Substring(sFileName.IndexOf("Image") + 6);
            picStaff.ImageLocation = sFileName;
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            FindStaffByStaffID(txtStaffID.Text.ToLower());
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            InsertStaffInfo();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (person != null)
                UpdateStaffInfo();
            else
                MessageBox.Show("You should choose the staff you want to change");
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (person != null)
            {
                DeleteStaff();
            }
            else
                MessageBox.Show("You should choose the staff you want to delete");
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void rdoUpdate_CheckedChanged(object sender, EventArgs e)
        {
            RefreshData();
            txtStaffID.Enabled = true;
            btnInsert.Enabled = false;
            pictureBox1.Enabled = true;
            btnDelete.Enabled = true;
            btnUpdate.Enabled = true;
            FindStaff(dgvStaffs.Rows[iIndex].Cells[0].Value.ToString());
        }

        private void dgvStaffs_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (rdoUpdate.Checked && dgvStaffs.CurrentRow.Index < dgvStaffs.Rows.Count - 1)
            {
                iIndex = dgvStaffs.CurrentRow.Index;
                string sStaffID = dgvStaffs.CurrentRow.Cells[0].Value.ToString();
                FindStaff(sStaffID);
            }
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }
    }
}